﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.Ccr.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using W3C.Soap;

namespace TasksLibrary
{
    public class TaskQueue
    {
        private Dictionary<int, Task> mTasks = new Dictionary<int, Task>();

        public TaskQueue()
        {

        }

        public bool NewTask(Task task)
        {
            try
            {
                if (task == null) return false;
                if (IsHaveTask(task.Id)) return false;

                mTasks.Add(task.Id, task);
            }
            catch (Exception) { }
            return false;
        }

        public void HandleMessage(object Message)
        {
            try
            {
                if (Message == null) return;

                bool canWork = false;
                Type messageType = Message.GetType();
                Type objType = typeof(object);
                for (int i = 0; i < 5; i++)
                {
                    if (messageType.IsGenericType)
                    {
                        if (messageType.GetGenericTypeDefinition() == typeof(Update<,>))
                        {
                            canWork = true;
                            break;
                        }
                    }
                    if (messageType.BaseType == objType) break;
                    messageType = messageType.BaseType;
                }

                if (canWork)
                {
                    var PropertiesMessage = Message.GetType().GetProperties();
                    TaskMessageRequest MessageBody = null;
                    foreach (var property in PropertiesMessage)
                        if (property.Name == "Body" && Inc.Types.CheckBaseType(property.PropertyType, typeof(TaskMessageRequest)))
                        {
                            MessageBody = (TaskMessageRequest)property.GetValue(Message, null);
                            break;
                        }

                    if (MessageBody != null)
                    {
                        //MessageBody.TaskId = BaseMessageBody.TaskId;
                        if (mTasks.ContainsKey(MessageBody.TaskId)) mTasks[MessageBody.TaskId].TryMessageComplete(MessageBody);
                    }
                }
            }
            catch (Exception)
            {
            }

        }

        public bool IsHaveTask(int TaskId)
        {
            try
            {
                if (mTasks.ContainsKey(TaskId)) return true;
            }
            catch (Exception) { }
            return false;
        }

        public Task this[int TaskId]
        {
            get
            {
                if (IsHaveTask(TaskId)) return mTasks[TaskId];
                return null;
            }
        }
    }
}
